import React, { useState, useMemo } from 'react';
import { View, Text, StyleSheet, ScrollView, Modal, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useStatistics } from '../hooks/useStatistics';
import { createCommonStyles } from '../styles/commonStyles';
import { useTheme } from '../hooks/useTheme';
import CalendarView from '../components/calendar/CalendarView';
import PlanItem from '../components/plan/PlanItem';
import ProgressBar from '../components/common/ProgressBar';
import usePlanStore from '../store/planStore';
import { getWeekRange, formatDate } from '../utils/dateUtils';
import { PLAN_STATUS } from '../utils/constants';

const StatisticsScreen = () => {
  const { todayStats, weekStats, monthStats } = useStatistics();
  const { plans, weeklyPlans, monthlyPlans, settings, getPlansByDate, togglePlanStatus } = usePlanStore();
  const { theme } = useTheme();
  const dynamicStyles = createCommonStyles(theme);
  const [selectedDate, setSelectedDate] = useState(null);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [viewMode, setViewMode] = useState('day'); // 'day', 'week', 'month'

  // 生成日历标记数据
  const markedDates = useMemo(() => {
    const marked = {};
    
    plans.forEach((plan) => {
      const date = plan.scheduledFor;
      if (!marked[date]) {
        marked[date] = {
          marked: true,
          dotColor: plan.status === PLAN_STATUS.COMPLETED ? theme.colors.success : theme.colors.primary,
        };
      } else {
        // 如果该日期有多个计划，根据完成情况决定颜色
        const datePlans = plans.filter(p => p.scheduledFor === date);
        const allCompleted = datePlans.every(p => p.status === PLAN_STATUS.COMPLETED);
        const hasCompleted = datePlans.some(p => p.status === PLAN_STATUS.COMPLETED);
        
        if (allCompleted) {
          marked[date].dotColor = theme.colors.success;
        } else if (hasCompleted) {
          marked[date].dotColor = theme.colors.warning; // 部分完成用橙色
        } else {
          marked[date].dotColor = theme.colors.primary;
        }
      }
    });

    // 标记选中的日期
    if (selectedDate) {
      marked[selectedDate] = {
        ...marked[selectedDate],
        selected: true,
        selectedColor: theme.colors.primary,
      };
    }

    return marked;
  }, [plans, selectedDate, theme]);

  // 获取选中日期的计划
  const selectedDatePlans = useMemo(() => {
    if (!selectedDate) return [];
    
    if (viewMode === 'day') {
      return getPlansByDate(selectedDate);
    } else if (viewMode === 'week') {
      const weekRange = getWeekRange(new Date(selectedDate), settings.weekStartDay);
      return plans.filter(
        p => p.scheduledFor >= weekRange.weekStart && p.scheduledFor <= weekRange.weekEnd
      );
    } else if (viewMode === 'month') {
      const month = formatDate(selectedDate, 'YYYY-MM');
      return plans.filter(p => p.scheduledFor.startsWith(month));
    }
    return [];
  }, [selectedDate, viewMode, plans, settings.weekStartDay, getPlansByDate]);

  // 获取选中日期的周计划
  const selectedWeekPlans = useMemo(() => {
    if (!selectedDate || viewMode !== 'week') return [];
    const weekRange = getWeekRange(new Date(selectedDate), settings.weekStartDay);
    return weeklyPlans.filter(
      p => p.weekStart === weekRange.weekStart
    );
  }, [selectedDate, viewMode, weeklyPlans, settings.weekStartDay]);

  // 获取选中日期的月计划
  const selectedMonthPlans = useMemo(() => {
    if (!selectedDate || viewMode !== 'month') return [];
    const month = formatDate(selectedDate, 'YYYY-MM');
    return monthlyPlans.filter(p => p.month === month);
  }, [selectedDate, viewMode, monthlyPlans]);

  const handleDayPress = (day) => {
    setSelectedDate(day.dateString);
    setShowDetailModal(true);
  };

  // 根据完成率获取颜色
  const getCompletionRateColor = (rate, theme) => {
    if (rate >= 80) {
      return theme.colors.success; // 高完成率：绿色
    } else if (rate >= 50) {
      return theme.colors.warning; // 中完成率：橙色
    } else {
      return theme.colors.error; // 低完成率：红色
    }
  };

  const getViewTitle = () => {
    if (!selectedDate) return '选择日期';
    
    if (viewMode === 'day') {
      return formatDate(selectedDate, 'YYYY年MM月DD日');
    } else if (viewMode === 'week') {
      const weekRange = getWeekRange(new Date(selectedDate), settings.weekStartDay);
      return `${weekRange.weekStart} ~ ${weekRange.weekEnd}`;
    } else {
      return formatDate(selectedDate, 'YYYY年MM月');
    }
  };

  return (
    <SafeAreaView style={[dynamicStyles.container, { backgroundColor: theme.colors.background }]} edges={['top']}>
      <ScrollView style={[dynamicStyles.content, { backgroundColor: theme.colors.background }]}>
        <View style={styles.header}>
          <Text style={[styles.title, { color: theme.colors.text }]}>数据统计</Text>
        </View>

        {/* 统计卡片 */}
        <View style={styles.statsContainer}>
          {/* 今日统计 */}
          <View style={[dynamicStyles.card, { backgroundColor: theme.colors.card }]}>
            <View style={styles.statsRow}>
              <View style={styles.statsHeader}>
                <Text style={styles.statsIcon}>📅</Text>
                <Text style={[styles.statsLabel, { color: theme.colors.text }]}>今日</Text>
              </View>
              <Text style={[styles.statsDescription, { color: theme.colors.textSecondary }]}>
                已完成 {todayStats.completed} 项，共 {todayStats.total} 项计划
              </Text>
            </View>
            <View style={styles.progressWrapper}>
              <ProgressBar 
                progress={todayStats.completionRate} 
                height={6}
                showText={false}
                style={styles.progressBar}
              />
              <Text style={[
                styles.statsRate,
                { color: getCompletionRateColor(todayStats.completionRate, theme) }
              ]}>
                {todayStats.completionRate}%
              </Text>
            </View>
          </View>

          {/* 本周统计 */}
          <View style={[dynamicStyles.card, { backgroundColor: theme.colors.card }]}>
            <View style={styles.statsRow}>
              <View style={styles.statsHeader}>
                <Text style={styles.statsIcon}>📆</Text>
                <Text style={[styles.statsLabel, { color: theme.colors.text }]}>本周</Text>
              </View>
              <Text style={[styles.statsDescription, { color: theme.colors.textSecondary }]}>
                已完成 {weekStats.completed} 项，共 {weekStats.total} 项计划
              </Text>
            </View>
            <View style={styles.progressWrapper}>
              <ProgressBar 
                progress={weekStats.completionRate} 
                height={6}
                showText={false}
                style={styles.progressBar}
              />
              <Text style={[
                styles.statsRate,
                { color: getCompletionRateColor(weekStats.completionRate, theme) }
              ]}>
                {weekStats.completionRate}%
              </Text>
            </View>
          </View>

          {/* 本月统计 */}
          <View style={[dynamicStyles.card, { backgroundColor: theme.colors.card }]}>
            <View style={styles.statsRow}>
              <View style={styles.statsHeader}>
                <Text style={styles.statsIcon}>🗓️</Text>
                <Text style={[styles.statsLabel, { color: theme.colors.text }]}>本月</Text>
              </View>
              <Text style={[styles.statsDescription, { color: theme.colors.textSecondary }]}>
                已完成 {monthStats.completed} 项，共 {monthStats.total} 项计划
              </Text>
            </View>
            <View style={styles.progressWrapper}>
              <ProgressBar 
                progress={monthStats.completionRate} 
                height={6}
                showText={false}
                style={styles.progressBar}
              />
              <Text style={[
                styles.statsRate,
                { color: getCompletionRateColor(monthStats.completionRate, theme) }
              ]}>
                {monthStats.completionRate}%
              </Text>
            </View>
          </View>

        </View>

        {/* 日历组件 */}
        <View style={styles.calendarSection}>
          <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>历史计划</Text>
          <Text style={[styles.sectionHint, { color: theme.colors.textSecondary }]}>点击日期查看该日期的计划详情</Text>
          <CalendarView 
            markedDates={markedDates}
            onDayPress={handleDayPress}
          />
        </View>
      </ScrollView>

      {/* 计划详情模态框 */}
      <Modal
        visible={showDetailModal}
        transparent={true}
        animationType="slide"
        onRequestClose={() => setShowDetailModal(false)}
      >
        <View style={[styles.modalOverlay, { backgroundColor: 'rgba(0, 0, 0, 0.5)' }]}>
          <View style={[styles.modalContent, { backgroundColor: theme.colors.card }]}>
            <View style={styles.modalHeader}>
              <Text style={[styles.modalTitle, { color: theme.colors.text }]}>{getViewTitle()}</Text>
              <TouchableOpacity
                style={[styles.closeButton, { backgroundColor: theme.colors.surface }]}
                onPress={() => setShowDetailModal(false)}
              >
                <Text style={[styles.closeButtonText, { color: theme.colors.text }]}>✕</Text>
              </TouchableOpacity>
            </View>

            {/* 视图模式切换 */}
            <View style={styles.viewModeContainer}>
              <TouchableOpacity
                style={[
                  styles.viewModeButton,
                  { backgroundColor: theme.colors.surface },
                  viewMode === 'day' && { backgroundColor: theme.colors.primary }
                ]}
                onPress={() => setViewMode('day')}
              >
                <Text style={[
                  styles.viewModeText,
                  { color: theme.colors.text },
                  viewMode === 'day' && { color: '#FFFFFF' }
                ]}>
                  日
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[
                  styles.viewModeButton,
                  { backgroundColor: theme.colors.surface },
                  viewMode === 'week' && { backgroundColor: theme.colors.primary }
                ]}
                onPress={() => setViewMode('week')}
              >
                <Text style={[
                  styles.viewModeText,
                  { color: theme.colors.text },
                  viewMode === 'week' && { color: '#FFFFFF' }
                ]}>
                  周
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[
                  styles.viewModeButton,
                  { backgroundColor: theme.colors.surface },
                  viewMode === 'month' && { backgroundColor: theme.colors.primary }
                ]}
                onPress={() => setViewMode('month')}
              >
                <Text style={[
                  styles.viewModeText,
                  { color: theme.colors.text },
                  viewMode === 'month' && { color: '#FFFFFF' }
                ]}>
                  月
                </Text>
              </TouchableOpacity>
            </View>

            <ScrollView style={styles.plansList}>
              {/* 日计划 */}
              {viewMode === 'day' && (
                <View>
                  <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>日计划</Text>
                  {selectedDatePlans.length === 0 ? (
                    <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>该日期没有计划</Text>
                  ) : (
                    selectedDatePlans.map((plan) => (
                      <PlanItem
                        key={plan.id}
                        plan={plan}
                        onToggle={() => togglePlanStatus(plan.id)}
                        showActions={false}
                      />
                    ))
                  )}
                </View>
              )}

              {/* 周计划 */}
              {viewMode === 'week' && (
                <View>
                  <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>周计划</Text>
                  {selectedWeekPlans.length === 0 ? (
                    <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>该周没有周计划</Text>
                  ) : (
                    selectedWeekPlans.map((plan) => (
                      <View key={plan.id} style={[dynamicStyles.card, { backgroundColor: theme.colors.card }]}>
                        <Text style={[styles.planTitle, { color: theme.colors.text }]}>{plan.title}</Text>
                        {plan.description && (
                          <Text style={[styles.planDescription, { color: theme.colors.textSecondary }]}>{plan.description}</Text>
                        )}
                        {plan.tasks && plan.tasks.length > 0 && (
                          <View style={styles.tasksList}>
                            {plan.tasks.map((task) => (
                              <View key={task.id} style={styles.taskItem}>
                                <Text style={[
                                  styles.taskText,
                                  { color: theme.colors.text },
                                  task.status === PLAN_STATUS.COMPLETED && [styles.taskCompleted, { color: theme.colors.textSecondary }]
                                ]}>
                                  {task.status === PLAN_STATUS.COMPLETED ? '✓' : '○'} {task.title}
                                </Text>
                              </View>
                            ))}
                          </View>
                        )}
                        <Text style={[styles.completionRate, { color: theme.colors.textSecondary }]}>
                          完成率: {plan.completionRate}%
                        </Text>
                      </View>
                    ))
                  )}
                  
                  <Text style={[styles.sectionTitle, { marginTop: 16, color: theme.colors.text }]}>本周日计划</Text>
                  {selectedDatePlans.length === 0 ? (
                    <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>本周没有日计划</Text>
                  ) : (
                    selectedDatePlans.map((plan) => (
                      <PlanItem
                        key={plan.id}
                        plan={plan}
                        onToggle={() => togglePlanStatus(plan.id)}
                        showActions={false}
                      />
                    ))
                  )}
                </View>
              )}

              {/* 月计划 */}
              {viewMode === 'month' && (
                <View>
                  <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>月计划</Text>
                  {selectedMonthPlans.length === 0 ? (
                    <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>该月没有月计划</Text>
                  ) : (
                    selectedMonthPlans.map((plan) => (
                      <View key={plan.id} style={[dynamicStyles.card, { backgroundColor: theme.colors.card }]}>
                        <Text style={[styles.planTitle, { color: theme.colors.text }]}>{plan.title}</Text>
                        {plan.description && (
                          <Text style={[styles.planDescription, { color: theme.colors.textSecondary }]}>{plan.description}</Text>
                        )}
                        {plan.tasks && plan.tasks.length > 0 && (
                          <View style={styles.tasksList}>
                            {plan.tasks.map((task) => (
                              <View key={task.id} style={styles.taskItem}>
                                <Text style={[
                                  styles.taskText,
                                  { color: theme.colors.text },
                                  task.status === PLAN_STATUS.COMPLETED && [styles.taskCompleted, { color: theme.colors.textSecondary }]
                                ]}>
                                  {task.status === PLAN_STATUS.COMPLETED ? '✓' : '○'} {task.title}
                                </Text>
                              </View>
                            ))}
                          </View>
                        )}
                        <Text style={[styles.completionRate, { color: theme.colors.textSecondary }]}>
                          完成率: {plan.completionRate}%
                        </Text>
                      </View>
                    ))
                  )}
                  
                  <Text style={[styles.sectionTitle, { marginTop: 16, color: theme.colors.text }]}>本月日计划</Text>
                  {selectedDatePlans.length === 0 ? (
                    <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>本月没有日计划</Text>
                  ) : (
                    selectedDatePlans.map((plan) => (
                      <PlanItem
                        key={plan.id}
                        plan={plan}
                        onToggle={() => togglePlanStatus(plan.id)}
                        showActions={false}
                      />
                    ))
                  )}
                </View>
              )}
            </ScrollView>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  header: {
    marginBottom: 24,
  },
  title: {
    fontSize: 32,
    fontWeight: 'bold',
  },
  statsContainer: {
    gap: 10,
  },
  statsRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  statsHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  statsIcon: {
    fontSize: 18,
    marginRight: 6,
  },
  statsLabel: {
    fontSize: 16,
    fontWeight: '600',
  },
  statsDescription: {
    fontSize: 12,
    lineHeight: 16,
    flex: 1,
    textAlign: 'right',
  },
  statsValue: {
    fontSize: 32,
    fontWeight: 'bold',
    marginBottom: 4,
  },
  progressWrapper: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  progressBar: {
    flex: 1,
  },
  statsRate: {
    fontSize: 14,
    fontWeight: '600',
    minWidth: 45,
    textAlign: 'right',
  },
  calendarSection: {
    marginTop: 24,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 8,
  },
  sectionHint: {
    fontSize: 12,
    marginBottom: 12,
  },
  modalOverlay: {
    flex: 1,
    justifyContent: 'flex-end',
  },
  modalContent: {
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 24,
    paddingBottom: 40,
    maxHeight: '90%',
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    flex: 1,
  },
  closeButton: {
    width: 32,
    height: 32,
    borderRadius: 16,
    justifyContent: 'center',
    alignItems: 'center',
  },
  closeButtonText: {
    fontSize: 18,
    lineHeight: 18,
  },
  viewModeContainer: {
    flexDirection: 'row',
    gap: 8,
    marginBottom: 20,
  },
  viewModeButton: {
    flex: 1,
    paddingVertical: 8,
    borderRadius: 8,
    alignItems: 'center',
  },
  viewModeButtonActive: {},
  viewModeText: {
    fontSize: 14,
    fontWeight: '500',
  },
  viewModeTextActive: {},
  plansList: {
    maxHeight: 400,
  },
  planTitle: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 4,
  },
  planDescription: {
    fontSize: 14,
    marginBottom: 8,
  },
  tasksList: {
    marginTop: 8,
    marginBottom: 8,
  },
  taskItem: {
    paddingVertical: 4,
    paddingLeft: 8,
  },
  taskText: {
    fontSize: 14,
  },
  taskCompleted: {
    textDecorationLine: 'line-through',
  },
  completionRate: {
    fontSize: 12,
    marginTop: 8,
  },
  emptyText: {
    fontSize: 14,
    fontStyle: 'italic',
    textAlign: 'center',
    paddingVertical: 20,
  },
});

export default StatisticsScreen;

